if exists(select * from sysobjects where name='p_calcgetpid')
  drop procedure p_calcgetpid



GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO





create     procedure p_calcgetpid
  @id integer,
  @depotid integer,
  @productid integer,
  @endqty decimal(18,4),
  @saleqty decimal(18,4),
  @bdate datetime,
  @resultid integer output,
  @resultqty decimal(18,4) output,
  @resultdate datetime output
as
begin
  set nocount on
  declare @sqty decimal(18,4)
  declare @pqty decimal(18,4)
  declare @tmpid integer
  declare @quantity decimal(18,4)
  declare @tmp_qty decimal(18,4)
  declare @tmpdate datetime
  set @tmp_qty = @endqty

  declare getpid cursor  local forward_only static read_only for
    select tid,abs(quantity),bdate from tt_bill 
      where bstate=1 and productid=@productid and (depotid=@depotid or @depotid=-1) 
        and ((bdate=@bdate and tid<@id) or bdate<@bdate) and ioflag*quantity > 0
      order by bdate desc, tid desc 
  open getpid
  fetch next from getpid into @tmpid,@quantity,@tmpdate
  while @@fetch_status = 0
  begin
    if (@tmp_qty >= @quantity)
    begin
      set @tmp_qty = @tmp_qty - @quantity
      set @resultid = @tmpid
      set @resultdate = @tmpdate
    end
    else
    begin
      if (@tmp_qty <> 0)
      begin
        set @resultid = @tmpid
        set @resultqty = @tmp_qty
        set @resultdate = @tmpdate
      end
      else
        set @resultqty = 0
      break
    end
    fetch next from getpid into @tmpid,@quantity,@tmpdate
  end
  close getpid
  deallocate getpid
  if @resultqty is null 
    set @resultqty = 0
end

GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

